#include "leveleditorwidget.h"
#include "modes/leveleditormode.h"
#include "levelObjects/level.h"
#include "document.h"
#include "application.h"

using namespace LevelModeWidgets;

LevelEditorWidget::LevelEditorWidget(QPointer<Modes::EditorMode> lem, QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);
	ui.treeWidgetLevelObjects->setLevelEditorMode(lem);

	QPointer<Modes::LevelEditorMode> pMode = qobject_cast<Modes::LevelEditorMode*>(lem);

	connect(lem, &Modes::LevelEditorMode::documentChanged, 
		this, &LevelModeWidgets::LevelEditorWidget::onDocumentChanged);
	connect(pMode, &Modes::LevelEditorMode::levelCreated, 
		this, &LevelModeWidgets::LevelEditorWidget::onLevelCreated);
	connect(pMode, &Modes::LevelEditorMode::levelDeleted, 
		this, &LevelModeWidgets::LevelEditorWidget::onLevelDeleted);
	connect(this, &LevelModeWidgets::LevelEditorWidget::selectedLevelChanged, 
		pMode, &Modes::LevelEditorMode::onSelectedLevelChanged);
	connect(this, &LevelModeWidgets::LevelEditorWidget::selectedLevelChanged, 
		ui.treeWidgetLevelObjects, &LevelObjectsTreeWidget::onSelectedLevelChanged);

	connect(ui.comboBoxCurrentLevel, SIGNAL(currentIndexChanged(int)), 
		this, SLOT(onSelectedLevelIndexChanged(int)));
}

void LevelModeWidgets::LevelEditorWidget::onDocumentChanged( QPointer<Document> document )
{
	if(!document)
	{
		ui.comboBoxCurrentLevel->clear();
	}
}

void LevelModeWidgets::LevelEditorWidget::onLevelCreated( QPointer<LevelObjects::AbstractLevelObject> level )
{
	ui.comboBoxCurrentLevel->addItem(level->name(), level->guid());
}

void LevelModeWidgets::LevelEditorWidget::onLevelDeleted( QPointer<LevelObjects::AbstractLevelObject> level )
{

}

void LevelModeWidgets::LevelEditorWidget::onSelectedLevelIndexChanged( int nIndex )
{
	ACQUIRE_DOC();

	QPointer<LevelObjects::AbstractLevelObject> levelObject;

	if(doc)
	{
		QUuid levelGuid = ui.comboBoxCurrentLevel->itemData(nIndex).toUuid(); 
		levelObject = doc->levelByGuid(levelGuid);
	}
	
	emit selectedLevelChanged(levelObject);
}
